from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import time, datetime

from google.appengine.api import users

from django.utils import simplejson

import csv
import pprint

from voteDb import voteDB

class NotFoundPageHandler(webapp.RequestHandler):
  def get(self):
    self.error(404)
    self.response.out.write('Not found.')

class AdminIndex(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if user:
      admin = voteDB.AdminCheck(user.email())
      if admin:
        ## load list of admin users, and an add box.
        adusers = voteDB.AdminUsers()
        rtv = "<b>Admin index</b><br/>"
        for ad in adusers:
          if ad.userid != user.email():
            rtv += ad.userid + "<a href='/admin/del?userid=" + ad.userid + "'>Delete</a><br />"
        rtv += "<form method='GET' action='/admin/add'><input type='text' length='40' name='userid'></input><input type='submit' value='Add'></input></form>"
      else:
#        if user.email() == "DanBUK81@gmail.com":
#          voteDB.AdminAdd(user.email())
        rtv = "You are not authorised. " + user.email()
    else:
      rtv = "<a href=\"%s\">Sign in or register</a>." % users.create_login_url("/admin/")
    self.response.out.write(rtv)

class AdminAdd(webapp.RequestHandler):
  def get(self):
    userid = self.request.get("userid")
    user = users.get_current_user()
    if user:
      admin = voteDB.AdminCheck(user.email())
      if admin:
        voteDB.AdminAdd(userid)
        self.response.out.write("Admin added. " + "<a href='/admin/'>Back</a>")
      else:
        self.error(401)
        self.response.out.write("You are not an Admin user.")
    else:
      self.error(401)
      self.response.out.write("Not Authorised")

class AdminDel(webapp.RequestHandler):
  def get(self):
    userid = self.request.get("userid")
    user = users.get_current_user()
    if user:
      admin = voteDB.AdminCheck(user.email())
      if admin:
        rv = voteDB.AdminDel(userid)
        if rv == True:
          self.response.out.write("Admin deleted. " + "<a href='/admin/'>Back</a>")
        else:
          self.response.out.write("Error.")
      else:
        self.error(401)
        self.response.out.write("You are not an Admin user.")
    else:
      self.error(401)
      self.response.out.write("Not Authorised")

class AdminImport(webapp.RequestHandler):
  def get(self):
    self.response.out.write("""
          <form action="/admin/import" method="post" enctype="multipart/form-data">
            <div>CSV:<br><input type="file" name="file" size="50"/></div>
            <div><input type="submit" value="Upload file"></div>
          </form>""")

  def post(self):
    csvdata = self.request.get('file')
    updated = 0
    inserted = 0
    for r in csv.reader(csvdata.splitlines()):
      #  def ParticipantAdd(uid, name, country, email, userid):
      rv = voteDB.ParticipantAdd(r[0], r[15], r[14], r[1], r[20])
      if rv == 1:
        updated = updated + 1
      else:
        inserted = inserted + 1
    rtv = "Inserted: " + str(inserted) + "\nUpdated: " + str(updated)
    self.response.headers['Content-Type'] = "text/plain"
    self.response.out.write(rtv)

class AdminLink(webapp.RequestHandler):
  def get(self):
    indexes = voteDB.DebateIndexes()
    indxs = {}
    updated = 0
    missing = 0
    for i in indexes:
      indxs[i.name] = i.key()
    pni = voteDB.ParticipantsNoIndex()
    for p in pni:
      try:
        p.index = indxs[p.country]
        p.put()
        updated = updated + 1
      except NameError:
        missing = missing + 1
    rtv = "Updated: " + str(updated) + "\nMissing: " + str(missing)
    self.response.headers['Content-Type'] = "text/plain"
    self.response.out.write(rtv)

application = webapp.WSGIApplication(
  [
    ('/admin/',       AdminIndex),
    ('/admin/add',    AdminAdd),
    ('/admin/del',    AdminDel),
    ('/admin/import', AdminImport),
    ('/admin/link',   AdminLink),
    ('/.*',           NotFoundPageHandler)
  ], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
